import {Gentle} from "@/common/tools/themeColor";

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
function parseTime(time: string | object | number, cFormat: string):string | null {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date: any
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string')) {
            if ((/^[0-9]+$/.test(time))) {
                // support "1548221490638"
                time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }

    let formatObj:any = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

/**
 * 验证对象是否为空
 * @param obj
 * @return Boolean true 代表不为空
 */
const emptyObj = (obj:object):boolean =>{
    return !!Object.keys(obj).length
}


/**
 * 枚举对象
 * @param { Object } enums
 * 枚举对应的key值
 * @param { String } key
 * 枚举值
 * @return { String }
 */
function getEnumValue(enums:any,key:string):unknown{
    const keys = Object.keys(enums);
    const values = Object.values(enums);
    return keys.indexOf(key) !== -1 ? values[keys.indexOf(key)] : '';
}


/**
 * 生成枚举对象
 * @param { Array } enums
 */
function enumObj(enums:any) {
    const labels = enums.map((item:any) => item.label);
    const values = enums.map((item:any) => item.value);
    return {
        labels,
        values,
        enums,
        getValueByLabel(label:any) {
            return values[labels.indexOf(label)];
        },
        getLabelByValue(value:any) {
            return labels[values.indexOf(value)];
        },
        getValue(valueOrLabel:any) {
            let index = values.indexOf(valueOrLabel);
            if (index < 0) {
                index = labels.indexOf((valueOrLabel));
            }
            return enums[index];
        }
    }
}

export { parseTime, enumObj, getEnumValue, emptyObj }
